/**
 * 1768. 交替合并字符串
 * https://leetcode-cn.com/problems/merge-strings-alternately/
 */
public class Solutions_1768 {
    public static void main(String[] args) {
//        String word1 = "abc", word2 = "pqr";  // output: "apbqcr"
//        String word1 = "ab", word2 = "pqrs";  // output: "apbqrs"
        String word1 = "abcd", word2 = "pq";  // output: "apbqcd"

        String result = mergeAlternately(word1, word2);
        System.out.println(result);
    }

    public static String mergeAlternately(String word1, String word2) {
        int i = 0, j = 0;
        char[] arr1 = word1.toCharArray();
        char[] arr2 = word2.toCharArray();
        int len1 = arr1.length, len2 = arr2.length;

        char[] res = new char[len1 + len2];

        int idx = 0;
        while (i < len1 && j < len2) {
            // 交替放置字符
            res[idx ++] = arr1[i ++];
            res[idx ++] = arr2[j ++];
        }
        // word1 还有剩余元素
        while (i < len1) {
            res[idx ++] = arr1[i ++];
        }
        // word2 还有剩余元素
        while (j < len2) {
            res[idx ++] = arr2[j ++];
        }
        return String.valueOf(res);
    }
}
